package config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.Filter;

/**
 *  加载xml 
 * Created by alex on 15-1-13.
 */
public class MyWebAppInitializer3 extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected WebApplicationContext createRootApplicationContext() {

        XmlWebApplicationContext webApplicationContext = new XmlWebApplicationContext();
        webApplicationContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        
        return webApplicationContext;
    }

    //支持添加 Filters

    /**
     *  HiddenHttpMethodFilter 支持PUT POST GET DELETE 等http方法
     *  CharacterEncodingFilter 支持设置编码格式
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {

        /**
         * encodingFilter 的设置等价于在servlet或是在spring Controller 方法里面设置
         *  @RequestMapping(value="XXXXX")
         *   public void XXXXX(User user,HttpServletRequestreq,HttpServletResponse resp) throws UnsupportedEncodingException
         *   {
         *      resp.setCharacterEncoding("UTF-8");
         *      req.setCharacterEncoding("UTF-8");
         *
         *   }
         */
        
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8"); // 设置请求的编码
        encodingFilter.setForceEncoding(true); //强制设置响应的编码和请求的编码相同
        
        


        return new Filter[]{new HiddenHttpMethodFilter(),encodingFilter};
    }
}
